import { Injectable, NestMiddleware, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { RedisService } from '../redis/redis.service'; // 根据实际路径调整

@Injectable()
export class RateLimiterMiddleware implements NestMiddleware {
  constructor(private readonly redisService: RedisService) {}

  async use(req: Request, res: Response, next: NextFunction) {
    const client = this.redisService.getClient();
    const ip = req.ip;

    const key = `ratelimit:${ip}`;
    const limit = 10; // 每分钟最多3次请求
    const ttl = 60; // 过期时间60秒

    const count = await client.incr(key);

    if (count === 1) {
      await client.expire(key, ttl);
    }

    if (count > limit) {
      throw new HttpException('Too many requests', HttpStatus.TOO_MANY_REQUESTS);
    }

    next();
  }
}